package flc.ast.fragment;

import android.app.Dialog;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;

import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.blankj.utilcode.util.TimeUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.footer.ClassicsFooter;
import com.scwang.smartrefresh.layout.header.ClassicsHeader;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadMoreListener;

import java.nio.file.WatchKey;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.Locale;

import flc.ast.AppConfig;
import flc.ast.R;
import flc.ast.activity.MovieDetailActivity;
import flc.ast.activity.MovieListActivity;
import flc.ast.adapter.CalendarAdapter;
import flc.ast.adapter.MovieListAdapter;
import flc.ast.adapter.WeekAdapter;
import flc.ast.bean.MyMovieListBean;
import flc.ast.bean.WeekBean;
import flc.ast.databinding.FragmentCalendarBinding;
import flc.ast.utils.AppSpUtils;
import stark.common.api.StkResApi;
import stark.common.base.IReqRetCallback;
import stark.common.basic.base.BaseNoModelFragment;
import stark.common.basic.event.EventStatProxy;
import stark.common.bean.StkResBean;

/**
 * A simple {@link Fragment} subclass.
 * Use the {@link CalendarFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class CalendarFragment extends BaseNoModelFragment<FragmentCalendarBinding> {

    private WeekAdapter weekAdapter;
    private List<WeekBean> listWeek = new ArrayList<>();
    private int oldPosition;
    private CalendarAdapter calendarAdapter;
    private Dialog myAddMovieListDialog;
    private EditText dialogAdd;
    private List<MyMovieListBean> listShow = new ArrayList<>();
    private MovieListAdapter movieListAdapter;
    private int page = 1;
    private int refreshTime = 200;


    @Override
    protected int onCreate() {
        return R.layout.fragment_calendar;
    }

    @Override
    protected void initView() {
        EventStatProxy.getInstance().statEvent1(getActivity(), mDataBinding.event1Container);
        EventStatProxy.getInstance().statEvent5(getActivity(), mDataBinding.event5Container);

        mDataBinding.ivAdd.setOnClickListener(this);

        mDataBinding.rvMovieList.setLayoutManager(new LinearLayoutManager(mContext, LinearLayoutManager.HORIZONTAL, false));
        movieListAdapter = new MovieListAdapter();
        mDataBinding.rvMovieList.setAdapter(movieListAdapter);
        movieListAdapter.setOnItemClickListener(this);

        mDataBinding.rvWeekList.setLayoutManager(new LinearLayoutManager(mContext, LinearLayoutManager.HORIZONTAL, false));
        weekAdapter = new WeekAdapter();
        mDataBinding.rvWeekList.setAdapter(weekAdapter);
        weekAdapter.setOnItemClickListener(this);

        mDataBinding.rvCalendarList.setLayoutManager(new GridLayoutManager(mContext, 2));
        calendarAdapter = new CalendarAdapter();
        mDataBinding.rvCalendarList.setAdapter(calendarAdapter);
        calendarAdapter.setOnItemClickListener(this);

        mDataBinding.refreshCalendarItem.setRefreshHeader(new ClassicsHeader(mContext));
        mDataBinding.refreshCalendarItem.setRefreshFooter(new ClassicsFooter(mContext));
        mDataBinding.refreshCalendarItem.setOnRefreshLoadMoreListener(new OnRefreshLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                page++;
                getData();
                mDataBinding.refreshCalendarItem.finishLoadMore(refreshTime);
            }

            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                page = 1;
                getData();
                mDataBinding.refreshCalendarItem.finishRefresh(refreshTime);
            }
        });

        //新建片单弹框
        addMovieListDialog();
    }

    @Override
    protected void onClickCallback(View v) {
        switch (v.getId()) {
            case R.id.ivAdd://新建歌单
                myAddMovieListDialog.show();
                break;
            //新建歌单弹框
            case R.id.tvDialogAddMovieListConfirm://确定
                addMovieList();
                break;
            case R.id.tvDialogAddMovieListCancel://取消
                myAddMovieListDialog.dismiss();
                break;
        }
    }

    @Override
    protected void onItemClickCallback(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
        if (adapter == movieListAdapter) {
            MovieListActivity.movieListId = movieListAdapter.getItem(position).getId();
            startActivity(MovieListActivity.class);
        } else if (adapter == weekAdapter) {
            weekAdapter.getItem(oldPosition).setSelected(false);
            oldPosition = position;
            weekAdapter.getItem(oldPosition).setSelected(true);
            weekAdapter.notifyDataSetChanged();
            page = 1;
            getData();
        } else if (adapter == calendarAdapter) {
            StkResBean bean = calendarAdapter.getItem(position);
            MovieDetailActivity.stkResBean = bean;
            startActivity(MovieDetailActivity.class);
        }
    }

    @Override
    protected void initData() {
        //日历
        SimpleDateFormat format = new SimpleDateFormat("dd");
        Calendar calendar = Calendar.getInstance(Locale.CHINA);
        calendar.setFirstDayOfWeek(Calendar.MONDAY);
        setData(calendar, Calendar.MONDAY, format, getString(R.string.week_text1));
        setData(calendar, Calendar.TUESDAY, format, getString(R.string.week_text2));
        setData(calendar, Calendar.WEDNESDAY, format, getString(R.string.week_text3));
        setData(calendar, Calendar.THURSDAY, format, getString(R.string.week_text4));
        setData(calendar, Calendar.FRIDAY, format, getString(R.string.week_text5));
        setData(calendar, Calendar.SATURDAY, format, getString(R.string.week_text6));
        setData(calendar, Calendar.SUNDAY, format, getString(R.string.week_text7));
        weekAdapter.setList(listWeek);
        getData();
        mDataBinding.tvYear.setText(TimeUtils.getNowString(new SimpleDateFormat("yyyy年")));
        mDataBinding.tvMonth.setText(TimeUtils.getNowString(new SimpleDateFormat("MM")));
    }

    @Override
    public void onResume() {
        super.onResume();
        getMovieListData();
    }

    //设置日期并判断是否为今天
    private void setData(Calendar calendar, int mode, SimpleDateFormat format, String week) {
        calendar.set(Calendar.DAY_OF_WEEK, mode);
        listWeek.add(new WeekBean(TimeUtils.date2String(calendar.getTime(), format), week));
        if (TimeUtils.isToday(calendar.getTime())) {
            oldPosition = listWeek.size() - 1;
            listWeek.get(oldPosition).setSelected(true);
        }
    }

    private void getData() {
        StkResApi.getTagResourceList(this, AppConfig.CALENDAR_DATA, StkResApi.createParamMap(0, 10), false, new IReqRetCallback<List<StkResBean>>() {
            @Override
            public void onResult(boolean success, String msg, @Nullable List<StkResBean> result) {
                if (success) {
                    if (result != null && result.size() > 0) {
                        if (page == 1) {
                            calendarAdapter.setList(result);
                        } else {
                            calendarAdapter.addData(result);
                        }
                    }
                }
            }
        });
    }

    private void getMovieListData() {
        listShow.clear();
        List<MyMovieListBean> listSp = AppSpUtils.getMovieList();
        if (listSp != null && listSp.size() > 0) {
            listShow.addAll(listSp);
            movieListAdapter.setList(listShow);
            mDataBinding.rvMovieList.setVisibility(View.VISIBLE);
        } else {
            mDataBinding.rvMovieList.setVisibility(View.GONE);
        }
    }

    private void addMovieList() {
        String movieListName = dialogAdd.getText().toString();
        if (TextUtils.isEmpty(movieListName)) {
            ToastUtils.showShort(R.string.please_input_movie_list_name);
            return;
        }
        myAddMovieListDialog.dismiss();
        //准备数据
        List<MyMovieListBean> listSave = new ArrayList<>();
        listSave.add(new MyMovieListBean(TimeUtils.getNowString(), movieListName, new ArrayList<>()));
        //保存数据
        List<MyMovieListBean> listSp = AppSpUtils.getMovieList();
        if (listSp != null && listSp.size() > 0) {
            listSp.addAll(0, listSave);
            AppSpUtils.saveMovieList(listSp);
        } else {
            AppSpUtils.saveMovieList(listSave);
        }
        getMovieListData();
    }

    //新建片单弹框
    private void addMovieListDialog() {
        myAddMovieListDialog = new Dialog(mContext, R.style.DialogStyle);
        View inflate = LayoutInflater.from(mContext).inflate(R.layout.dialog_add_movie_list, null);
        myAddMovieListDialog.setContentView(inflate);
        myAddMovieListDialog.setCancelable(true);
        Window dialogWindow = myAddMovieListDialog.getWindow();
        //设置Dialog从窗体底部弹出
        dialogWindow.setGravity(Gravity.CENTER);
        DisplayMetrics dm = getResources().getDisplayMetrics();
        //获得窗体的属性
        WindowManager.LayoutParams lp = dialogWindow.getAttributes();
        lp.width = (int) (dm.widthPixels * 1.0);
        // 将属性设置给窗体
        dialogWindow.setAttributes(lp);
        TextView right = inflate.findViewById(R.id.tvDialogAddMovieListConfirm);
        TextView cancel = inflate.findViewById(R.id.tvDialogAddMovieListCancel);
        dialogAdd = inflate.findViewById(R.id.etDialogAddMovieListText);
        right.setOnClickListener(this);
        cancel.setOnClickListener(this);
    }

}